package huoye.shops.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.service.autofill.RegexValidator;
import android.support.design.widget.TabLayout;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.codeideology.android.log.LogUtils;


import org.intellij.lang.annotations.RegExp;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class StockUtils {

    public static String setTimeStyle(long time) {
        if (time <= 9) {
            return "0" + time;
        }
        return time + "";
    }


    //把List的数据 逗号 分割开
    public static String listToString(List<String> stringList){
        if(stringList==null) {
            return null;
        }
        StringBuilder result = new StringBuilder();
        boolean flag=false;
        for(String string : stringList) {
            if(flag) {
                result.append(",");
            }else{
                flag = true;
            }
            result.append(string);
        }
        return result.toString();
    }




    //利用了Set不重复的特性去掉list重复数据
    public static List removeDuplicateWithOrder(List list) {
        Set set = new HashSet();
        List newList = new ArrayList();
        for (Iterator iter = list.iterator(); iter.hasNext(); ) {
            Object element = iter.next();
            if (set.add(element))
                newList.add(element);
        }
        return newList;

    }



     /***
     * 获取url 指定name的value;
     * @param url
     * @param name
     * @return
     */
    public static String getValueByName(String url, String name) {
        String result = "";
        int index = url.indexOf("?");
        String temp = url.substring(index + 1);
        String[] keyValue = temp.split("&");
        for (String str : keyValue) {
            if (str.contains(name)) {
                result = str.replace(name + "=", "");
                break;
            }
        }
        return result;
    }


        //把路劲制定的图片转换成Base64

    public static String bitmapToBase64(String fileName) throws IOException {
        Bitmap bitmap = null;
        bitmap = BitmapFactory.decodeFile(fileName);
        String strBase64 = getBitmapStrBase64(bitmap);
        return strBase64;

    }

    //把Bitmap换成Base64
    public static String getBitmapStrBase64(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 60, baos);
        byte[] bytes = baos.toByteArray();
        return Base64.encodeToString(bytes, Base64.NO_WRAP);
    }


    //侵染状态栏
    public static void noBar(Activity activity) {
        //透明状态栏
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //透明导航栏
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
    }


    public static void reflex(final TabLayout tabLayout) {
        //了解源码得知 线的宽度是根据 tabView的宽度来设置的
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                try {
                    //拿到tabLayout的mTabStrip属性
                    Field mTabStripField = tabLayout.getClass().getDeclaredField("mTabStrip");
                    mTabStripField.setAccessible(true);

                    LinearLayout mTabStrip = (LinearLayout) mTabStripField.get(tabLayout);

                    int dp10 = dip2px(tabLayout.getContext(), 10);

                    for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                        View tabView = mTabStrip.getChildAt(i);

                        //拿到tabView的mTextView属性
                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                        mTextViewField.setAccessible(true);

                        TextView mTextView = (TextView) mTextViewField.get(tabView);

                        tabView.setPadding(0, 0, 0, 0);

                        //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度
                        int width = 0;
                        width = mTextView.getWidth();
                        if (width == 0) {
                            mTextView.measure(0, 0);
                            width = mTextView.getMeasuredWidth();
                        }

                        //设置tab左右间距为10dp  注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                        params.width = width;
                        params.leftMargin = dp10;
                        params.rightMargin = dp10;
                        tabView.setLayoutParams(params);

                        tabView.invalidate();
                    }

                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });

    }


    public static String getTime(Date date, String dateFormat) {
        SimpleDateFormat format = new SimpleDateFormat(dateFormat);
        return format.format(date);
    }


    public static String dataAddMonth(Date date, int month) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.MINUTE, month);
        return formatDateTime(c.getTime());
    }


    /**
     * 两个时间相差距离多少天   如果多加 *60  会除尽。所以拿一天59 去比
     */
    public static long getDistanceTimeDay(Date one, Date two) {
        long day = 0;

        try {
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff;
            if (time1 < time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            day = diff / (24 * 60 * 1000);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.d("test", e.getMessage());
        }
        return day;

    }


    /**
     * 得到几天前的时间
     *
     * @param d
     * @param day
     * @return
     */
    public static Date getDateBefore(Date d, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
        return now.getTime();
    }


/*    *//**
     * 得到7天前的时间
     * @return
     *//*
    public static String getSevenDateBefore(){
        Calendar now = Calendar.getInstance();
        Date date = new Date(System.currentTimeMillis());//获取当前时间
        now.setTime(date);
        now.set(Calendar.DATE,now.get(Calendar.DATE)-7);
        return getTime(now.getTime(),FORMAT_YYYY_MM_DD).toString();
    }*/


    /**
     * 获取一个月前的日期
     *
     * @return
     */
    public static String getLastMonth() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        Date date = new Date(System.currentTimeMillis());//获取当前时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, -1);
        String monthAgo = simpleDateFormat.format(calendar.getTime());
        return monthAgo;
    }


    /**
     * 得到几天后的时间
     *
     * @param d
     * @param day
     * @return
     */
    public static Date getDateAfter(Date d, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
        return now.getTime();
    }


    //转换时间格式   2017-07-21 09:00
    public static String getStyleTime(String time) {
        Long LongTime = Long.valueOf(time);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date d1 = new Date(LongTime * 1000);
        return format.format(d1);
    }


    //转换时间格式   2017-07-21 09:00
    public static String getStyleTimeDay(String time) {
        Long LongTime = Long.valueOf(time);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = new Date(LongTime * 1000);
        return format.format(d1);
    }


    //身份证隐藏中间数字
    public static String hideIdNumber(String idNumber) {
        String showId = idNumber.substring(0, 3) + "***********" + idNumber.substring(14);


        return showId;
    }

    //转换时间格式
    public static String getDay(int lo) {
        SimpleDateFormat format = new SimpleDateFormat("dd");
        Date d1 = new Date(lo * 1000);
        return format.format(d1);
    }


    //转换时间格式
    public static String getYeasMonthDay(int lo) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        Date d1 = new Date(lo * 1000);
        return format.format(d1);
    }


    //log转 date
    public static Date getDate(long lo) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        Date d1 = new Date(lo * 1000);
        return d1;
    }


    //手机号码,固话正则表达式
    public static boolean isPhoneCorrect(String phone) {
        /*Pattern p =
                Pattern.compile("^(((13[0-9])|(15([0-3]|[5-9])|170)|(18[0,1,2,3,0-9])|(17[0,1,2,3,6,0-9])|(147))\\d{8})|(0\\d{2}-\\d{8})|(0\\d{3}-\\d{8})$");
        Matcher m = p.matcher(phone);*/
        if (phone.toString().length() == 11) {
            return true;
        }
        return false;
    }

        //保留小数点后面2位   会自动四舍五入
      public static String moenyStyle(String Moeny) {
            Double valueOf = Double.valueOf(Moeny);
            BigDecimal bd = new BigDecimal(valueOf);
            bd = bd.setScale(2, BigDecimal.ROUND_DOWN);
            return bd+"";
        }


        //保留小数点后面 把带0 的去掉 新
      public static String moenyStyleNoZero(String s) {
         if(s.indexOf(".") > 0){
                s = s.replaceAll("0+?$", "");//去掉多余的0
                s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
            }
            return  s;

        }

    //保留小数点后面 2位
   /* public static String moenyStyle(String s) {
        Double doubleValue = Double.valueOf(s);
        // 保留4位小数
        java.text.DecimalFormat df = new java.text.DecimalFormat("#.0000");
        String result = df.format(doubleValue);

        // 截取第一位
        String index = result.substring(0, 1);

        if (".".equals(index)) {
            result = "0" + result;
        }

        // 获取小数 . 号第一次出现的位置
        int inde = firstIndexOf(result, ".");

        // 字符串截断
        return result.substring(0, inde + 3);
    }*/

    /**
     * 查找字符串pattern在str中第一次出现的位置
     *
     * @param str
     * @param pattern
     * @return
     */
    public static int firstIndexOf(String str, String pattern) {
        for (int i = 0; i < (str.length() - pattern.length()); i++) {
            int j = 0;
            while (j < pattern.length()) {
                if (str.charAt(i + j) != pattern.charAt(j))
                    break;
                j++;
            }
            if (j == pattern.length())
                return i;
        }
        return -1;
    }


        //去掉小数点后面一位
        public static BigDecimal noDecimal(String Moeny) {
            Double valueOf = Double.valueOf(Moeny);
            BigDecimal bd = new BigDecimal(valueOf);
            bd = bd.setScale(0, BigDecimal.ROUND_DOWN);
            return bd;
        }



        //把字符串转为日期
        public static Date converToDate(String strDate) throws Exception {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return df.parse(strDate);
        }


        /**
         * 获取当前日期 + 10年
         *
         * @param
         * @return
         */
    public static String getYearAdd() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.YEAR, +10);
        String monthAgo = simpleDateFormat.format(calendar.getTime());
        return monthAgo;
    }


    //获取当前系统时间
    public static String getCurrentTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        return formatter.format(curDate);
    }


    //获取当前系统时间
    public static String getCurrentTimeDate(Date curDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM/dd   E");
        //curDate(System.currentTimeMillis());//获取当前时间
        return formatter.format(curDate);
    }


    //获取月
    public static String getCurrentYearMonthTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        return formatter.format(curDate);
    }

    //获取月
    public static String getCurrentYearMonthStringTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        return formatter.format(curDate);
    }


    //获取年
    public static String getCurrentYearTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        return formatter.format(curDate);
    }


    //获取年月日
    public static String getYearMonthDayTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        return formatter.format(curDate);
    }


    //获取年日
    public static String getCurrentMonthDayTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("MM/dd");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        return formatter.format(curDate);
    }


    //获取月
    public static int getCurrentMonthTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("MM");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        return Integer.valueOf(formatter.format(curDate));
    }


    public static String getWhatDay() {
        String mWay;
        final Calendar c = Calendar.getInstance();
        //  c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
        if ("1".equals(mWay)) {
            mWay = "天";
        } else if ("2".equals(mWay)) {
            mWay = "一";
        } else if ("3".equals(mWay)) {
            mWay = "二";
        } else if ("4".equals(mWay)) {
            mWay = "三";
        } else if ("5".equals(mWay)) {
            mWay = "四";
        } else if ("6".equals(mWay)) {
            mWay = "五";
        } else if ("7".equals(mWay)) {
            mWay = "六";
        }
        return "星期" + mWay;
    }


    //随机生成六位数
    public static int getRandomGeneration() {
        int numcode = (int) ((Math.random() * 9 + 1) * 100000);
        return numcode;
    }

    //当前时间戳
    public static String getTimestamp() {
        long time = System.currentTimeMillis() / 1000;//获取系统时间的10位的时间戳
        String str = String.valueOf(time);
        return str;
    }


    //毫秒转分钟
    public static String timeParse(long duration) {
        String time = "";

        long minute = duration / 60000;


        if (minute < 10) {
            time += "0";
        }
        time += minute;

        return time;
    }

    //date 转毫秒
    public static Long date2Millisecond(Date date) {
        return date.getTime();
    }


    //截取时分
    private static SimpleDateFormat DATE_FORMAT_HM = new SimpleDateFormat("HH:mm");
    private static SimpleDateFormat DATE_FORMAT_DD = new SimpleDateFormat("dd");
    private static SimpleDateFormat DATE_FORMAT_YMDHMS = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    private static SimpleDateFormat DATE_FORMAT_YMDHMS_NO_HOUR = new SimpleDateFormat("yyyy-MM-dd");
    private static SimpleDateFormat DATE_FORMAT_YEAR_MONTH_DAY = new SimpleDateFormat("yyyy/MM/dd");
    private static SimpleDateFormat DATE_FORMAT_DAY_ACROSS = new SimpleDateFormat("MM-dd");
    private static SimpleDateFormat DATE_FORMAT_DAY_ACROSS_TWO = new SimpleDateFormat("MM/dd");
    private static SimpleDateFormat DATE_FORMAT_DAY_FOUND = new SimpleDateFormat("MM/dd HH:mm");


    public static String formatDateTime(Date date) {
        String strDate = "";

        try {
            strDate = DATE_FORMAT_HM.format(date);
        } catch (Exception var3) {
            var3.printStackTrace();
        }

        return strDate;
    }


    public static String formatDateTimeFound(Date date) {
        String strDate = "";

        try {
            strDate = DATE_FORMAT_DAY_FOUND.format(date);
        } catch (Exception var3) {
            var3.printStackTrace();
        }

        return strDate;
    }

    //获取天数
    public static String formatDate(Date date) {
        String strDate = "";

        try {
            strDate = DATE_FORMAT_DD.format(date);
        } catch (Exception var3) {
            var3.printStackTrace();
        }

        return strDate;
    }


    //获取 yyyy-MM-dd HH:mm
    public static String formatMinuteDate(Date date) {
        String strDate = "";

        try {
            strDate = DATE_FORMAT_YMDHMS.format(date);
        } catch (Exception var3) {
            var3.printStackTrace();
        }

        return strDate;
    }


    //获取 yyyy-MM-dd
    public static String formatMinuteDateNoHour(Date date) {
        String strDate = "";

        try {
            strDate = DATE_FORMAT_YMDHMS_NO_HOUR.format(date);
        } catch (Exception var3) {
            var3.printStackTrace();
        }

        return strDate;
    }

    //获取 yyyy/MM/dd
    public static String formatYearMonthDayDate(Date date) {
        String strDate = "";

        try {
            strDate = DATE_FORMAT_YEAR_MONTH_DAY.format(date);
        } catch (Exception var3) {
            var3.printStackTrace();
        }

        return strDate;
    }


    //获取 MM-dd
    public static String formatFormatDayDateacross(Date date) {
        String strDate = "";

        try {
            strDate = DATE_FORMAT_DAY_ACROSS.format(date);
        } catch (Exception var3) {
            var3.printStackTrace();
        }

        return strDate;
    }

    //获取 MM/dd
    public static String formatFormatDayDateacrossTwo(Date date) {
        String strDate = "";

        try {
            strDate = DATE_FORMAT_DAY_ACROSS_TWO.format(date);
        } catch (Exception var3) {
            var3.printStackTrace();
        }

        return strDate;
    }


    /**
     * 获取一个月前的日期
     *
     * @param date 传入的日期
     * @return
     */
    public static String getMonthAgo(Date date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, -1);
        String monthAgo = simpleDateFormat.format(calendar.getTime());
        return monthAgo;
    }


    /**
     * 获取一周前的日期
     *
     * @param date 传入的日期
     * @return
     */
    public static String getDayAgo(Date date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -7);
        String monthAgo = simpleDateFormat.format(calendar.getTime());
        return monthAgo;
    }


    public static String formatMessageTime(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.get(Calendar.WEEK_OF_MONTH);
        long now = calendar.getTimeInMillis();
        calendar.setTime(date);
        long past = calendar.getTimeInMillis();
        long time = (now - past) / 1000L;
        StringBuffer sb = new StringBuffer();
        return time > 0L && time < 60L ? sb.append(time + "秒前").toString() : (time > 60L && time < 3600L ? sb.append(time / 60L + "分钟前").toString() : (time >= 3600L && time < 86400L ? sb.append(time / 3600L + "小时前").toString() : (time >= 86400L && time < 172800L ? sb.append("昨天").toString() : (time >= 172800L && time < 259200L ? sb.append("前天").toString() : (time >= 259200L ? formatDateTimeFound(date) : formatDateTime(date))))));
    }


    //view 转bitmap

    public static Bitmap convertViewToBitmap(View view) {

        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

        view.buildDrawingCache();

        Bitmap bitmap = view.getDrawingCache();

        return bitmap;

    }


/*    public static void reflex(final TabLayout tabLayout) {
        //了解源码得知 线的宽度是根据 tabView的宽度来设置的
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                try {
                    //拿到tabLayout的mTabStrip属性
                    Field mTabStripField = tabLayout.getClass().getDeclaredField("mTabStrip");
                    mTabStripField.setAccessible(true);

                    LinearLayout mTabStrip = (LinearLayout) mTabStripField.get(tabLayout);

                    int dp10 = dip2px(tabLayout.getContext(), 10);


                    for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                        View tabView = mTabStrip.getChildAt(i);

                        //拿到tabView的mTextView属性
                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                        mTextViewField.setAccessible(true);

                        TextView mTextView = (TextView) mTextViewField.get(tabView);

                        tabView.setPadding(0, 0, 0, 0);

                        //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度
                        int width = 0;
                        width = mTextView.getWidth();
                        if (width == 0) {
                            mTextView.measure(0, 0);
                            width = mTextView.getMeasuredWidth();
                        }

                        //设置tab左右间距为10dp  注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                        params.width = width;
                        params.leftMargin = dp10;
                        params.rightMargin = dp10;
                        tabView.setLayoutParams(params);

                        tabView.invalidate();
                    }

                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });

    }*/


    public static int dip2px(Context context, float dipValue) {

        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }


    //弹窗在中间
    public static void showToast(Activity activity, String text) {
        Toast toast = Toast.makeText(activity, text, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }


    //获得本周一0点时间
    @SuppressLint("WrongConstant")
    public static long getTimesWeekmorning() {
        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        return (cal.getTimeInMillis() / 1000);
    }


    //获得本周日24点时间
    @SuppressLint("WrongConstant")
    public static long getTimesWeeknight() {
        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        return ((cal.getTime().getTime() + (7 * 24 * 60 * 60 * 1000)) / 1000);
    }






}
